package com.cow.framework.core.message;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cow.framework.core.base.BaseComponent;

/**
 * 消息控制类
 * 
 * @author yangsj
 */

@RestController
@EnableAutoConfiguration
@Transactional
@RequestMapping(value="/communication")
public class MessageController extends BaseComponent{
	@Autowired
	MessageService messageService;

	/**检索我的消息*/
	@RequestMapping(value="/getMyMessage")
	public Object getMyMessage(@RequestBody Map parmMap){
		Sort sort = new Sort(Direction.DESC, "sendTime");
	    Pageable pageable = new PageRequest((Integer)parmMap.get("page") - 1, (Integer)parmMap.get("size"),sort);
		Page<Message> result = messageService.getMyMessage(pageable);
		
		return result;
	}
	
	/**检索我的未读消息*/
	@RequestMapping(value="/getNoReadMessage")
	public Object getNoReadMessage(@RequestBody Map parmMap){
		Sort sort = new Sort(Direction.DESC, "sendTime");
	    Pageable pageable = new PageRequest((Integer)parmMap.get("page") - 1, (Integer)parmMap.get("size"),sort);
		Page<Message> result = messageService.getNoReadMessage(pageable);
		
		return result;
	}
	
	/**检索我的未读消息*/
	@RequestMapping(value="/countNoRead")
	public Object countNoRead(){
		Integer count = messageService.countNoRead(super.getCurUserId());
		Map map = new HashMap();
		map.put("noReadNum", count);
		return map;
	}
	
	/**阅读消息*/
	@RequestMapping(value="/readMessage")
	public Object readMessage(@RequestParam Integer messageId){
		Message message = messageService.getMessageById(messageId);
		message.setReceiveTime(new Date());
		message.setStatus(2);
		messageService.saveMessage(message);
		return "success";
	}
}
